<template>
  <div class="collect">
    <div class="sticky left-0 right-0 top-0 z-9 h-full bg-hex-ffffff">
      <div class="sticky left-0 right-0 top-0 z-9 h-full bg-hex-ffffff">
        <div class="relative">
          <div class="z-999 flex items-center justify-between px-20rpx" :style="{ paddingTop: `${searchBarTop}px` }" @click.stop="goback">
            <uni-icons type="back" size="28" />
            <span class="text-center text-36rpx font-600">收藏</span>
            <div class="text-hex-fff">111</div>
          </div>
        </div>
        <div class="mt-36rpx flex items-center justify-center">
          <div class="h-64rpx w-392rpx flex items-center justify-between rounded-60rpx bg-hex-ABCD03 px-4rpx text-28rpx text-hex-fff">
            <div v-for="item in toptablist" :key="item.id" class="h-56rpx w-192rpx rounded-56rpx text-center leading-56rpx"
                 :class="{ 'text-hex-ABCD03 bg-hex-fff': tabIndex === item.id }" @click="changeIndex(item.id)">{{ item.text }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="p-32rpx">
      <div class="mt-44rpx">
        <s-waterfall v-if="collectList.length>0" :datalist="collectList" :column="2">
          <template #default="{ item }">
            <div class="mb-24rpx box-border w-326rpx rounded-32rpx pr-32rpx" @click="goTeaDetail(item)">
              <div class="bg-water max-h-500rpx w-326rpx flex items-center justify-center overflow-hidden rounded-xl bg-hex-FAF9F8"
                   :class="[tabIndex===1?'py-0rpx':'py-40rpx']">
                <image
                  class="will-change rounded-24rpx"
                  :class="[tabIndex===1?'w-326rpx h-100%':'h-190rpx w-130rpx']"
                  lazy-load
                  :src="item.image" mode="widthFix" />
              </div>
              <div class="multiLine-hiddle mt-10rpx w-320rpx" :class="[tabIndex===1?'text-28rpx font-500':'text-24rpx']">
                {{ item.title }}
              </div>
              <div v-if="tabIndex!==1">
                <sapn class="mr-10rpx text-30rpx font-600 text-hex-ff4d4e">¥{{ item.productPrice }}</sapn>
                <sapn class="text-24rpx text-hex-999999 line-through">¥{{ item.cost }}</sapn>
              </div>
              <div class="mb-32rpx mt-16rpx flex items-center justify-between">
                <div v-if="tabIndex!==1" class="mr-32rpx text-24rpx text-hex-999999 line-through">已售{{ item.saleNum??0 }}</div>
                <div v-else class="flex items-center">
                  <image class="mr-24rpx h-44rpx w-44rpx rounded-100%" :src="item.avatar_url" mode="scaleToFill" />
                  <span class="text-24rpx text-hex-7C8699">{{ item.nickname }}</span>
                </div>
                <image
                  :src="`${cdnUrl}/svgicons/pl_liketrue.svg${imgVersion}`"
                  class="mt--20rpx h-34rpx w-36rpx"
                  mode="scaleToFill"
                  @click.stop="cancelCollect(item)"
                />
              </div>
            </div>
          </template>
        </s-waterfall>
        <div v-else>
          <div class="flex flex-col items-center justify-center">
            <image
              :src="`${cdnUrl}/imgs/noOpen/noText.png${imgVersion}`"
              mode="scaleToFill"
              class="h-300rpx w-300rpx"
            />
            <div class="mb-64rpx text-28rpx text-hex-7C8699">暂无数据</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang='ts' setup>
import { useUserStore } from '@/stores/user'

let searchBarTop: any = $ref('24')

onLoad(() => {
  // #ifndef H5
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top
  // #endif
})
const userInfo = useUserStore()
const toptablist = [{ id: 1, text: '广场' }, { id: 2, text: '茶饮' }, { id: 3, text: '商城' }]
const goback = () => {
  uni.navigateBack({
    delta: 1,
  })
}
let tabIndex: any = $ref(1)
let collectList: any = $ref([])
let pageNo = $ref(1)
let tegTotalPage: any = $ref()
//重置分页和数据
const resetPageData = () => {
  pageNo = 1
  offset = 0
  collectList = []
}
//请求商城茶饮收藏
const shopCollectList = async () => {
  const { data, error, status } = await Fetch('/qqyapi/product/product/collect/list', {
    method: 'post',
    headers: {
      userId: userInfo.user.id,
      AppType: tabIndex === 2 ? tabIndex : 3, //商城为3 ，茶饮为2
    },
    data: { pageNo, pageSize: 10 },
  })
  if (status === 200 && data.code === 0) {
    let filterData = data.result.list.map((item: any) => {
      return {
        ...item,
        image: item.productImage,
        title: item.productName,
      }
    })
    collectList = [...collectList, ...filterData]
    if (collectList.length < data.result.total) {
      isLoadMore = true
      return
    }
    isLoadMore = false
  }
}
//请求广场收藏
let offset = $ref(0)
let isLoadMore = $ref(false)
const getSquareList = async () => {
  const { data, status } = await Fetch('/api/s/t/user_collect', {
    method: 'post',
    headers: { userId: userInfo.user.id, timestamp: new Date().getTime() },
    data: { offset, limit: 10 },
  })
  if (status !== 200 || data.code !== 0) {return}
  let filterData = data.result.dataList.map(item => {
    return { ...item, image: item.cover_image }
  })
  collectList = [...collectList, ...filterData]
  if (collectList.length < data.result.total) {
    isLoadMore = true
    return
  }
  isLoadMore = false
}
const isGetData = () => {
  //上拉加载判断 2 3 请求商城
  tabIndex === 1 ? getSquareList() : shopCollectList()
}
const changeIndex = (index) => {
  resetPageData()
  tabIndex = index
  //切换tab请求接口
  isGetData()
}


const goTeaDetail = (item) => {
  let IsGoUrl = {
    '1': `/pages-square/articledetail?articleId=${item.article_id}`,
    '2': item.unionFlag === 1 ? `/pages-tea/doubleDetails?productId=${item.productId}` : `/pages-tea/details?productId=${item.productId}`,
    '3': `/pages-shop/goodsdetails?productId=${item.productId}`,
  }
  navTo(IsGoUrl[tabIndex])
}

//取消收藏茶饮和商城
const cancelCollectShop = async (productId) => {
  const { data, error, status } = await Fetch('/qqyapi/product/product/collect/delete', {
    method: 'post',
    headers: {
      userId: userInfo.user.id,
      AppType: tabIndex === 2 ? tabIndex : 3, //商城为3 ，茶饮为2
    },
    data: {
      productId,
    },
  })
  if (status === 200 && data.code === 0) {
    if (data.result) {
      uni.showToast({
        title: '取消成功',
      })
      //从collectList中截取当前productId的选项
      collectList.splice(collectList.findIndex(item => item.productId === productId), 1)
    }
  }
}
//广场的取消收藏
const cancelCollectSquare = async (id) => {
  const { data, status } = await Fetch('/api/s/t/user_collect', {
    method: 'DELETE',
    headers: {
      userId: userInfo.user.id,
    },
    data: { id },
  })
  if (status === 200 && data.code === 0) {
    uni.showToast({
      title: '取消成功',
    })
    //从collectList中截取当前id的选项
    collectList.splice(collectList.findIndex(item => item.user_collect__id === id), 1)
  }
}
//取消收藏
const cancelCollect = (item) => {
  tabIndex === 1 ? cancelCollectSquare(item.user_collect__id) : cancelCollectShop(item.productId)
}

const getMoreData = () => {
  if (isLoadMore) {
    pageNo++
    offset += 10
    isGetData()
  }
}

onReachBottom(() => {
  getMoreData()
})
onMounted(() => {
  getSquareList()
})
</script>

<style lang='scss'>
.collect{
  .multiLine-hiddle{
    overflow : hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break:break-all;
  }
}
</style>
